package main

import (
	"fmt"
	"github.com/xwb1989/sqlparser"
)

func main() {

	sql := "SELECT id, username, password FROM users u WHERE u.id = 60 and username = 'admin' order by create_time desc limit 0, 5"

	stmt, err := sqlparser.Parse(sql)
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return
	}

	switch stmt := stmt.(type) {
	case *sqlparser.Select:
		// 解析from子句，得到users u
		from, as := ResolveFrom(stmt)
		fmt.Printf("from: %v, as: %v\n", from, as)
		selectStr := ResolveSelect(stmt)
		fmt.Printf("select: %v\n", selectStr)
		whereStr := ResolveWhere(stmt)
		fmt.Printf("where: %v\n", whereStr)
		orderByStr := ResolveOrderBy(stmt)
		fmt.Printf("order by: %v\n", orderByStr)
		groupByStr := ResolveGroupBy(stmt)
		fmt.Printf("group by: %v\n", groupByStr)
		limitStr := ResolveLimit(stmt)
		fmt.Printf("limit: %v\n", limitStr)
	case *sqlparser.Insert:
	}
}

func ResolveLimit(stmt *sqlparser.Select) string {
	limit := stmt.Limit
	buf := sqlparser.NewTrackedBuffer(nil)
	limit.Format(buf)
	return buf.String()
}

func ResolveGroupBy(stmt *sqlparser.Select) string {
	groupBy := stmt.GroupBy
	buf := sqlparser.NewTrackedBuffer(nil)
	groupBy.Format(buf)
	return buf.String()
}

func ResolveOrderBy(stmt *sqlparser.Select) string {
	orderBy := stmt.OrderBy
	buf := sqlparser.NewTrackedBuffer(nil)
	orderBy.Format(buf)
	return buf.String()
}

func ResolveWhere(stmt *sqlparser.Select) string {
	where := stmt.Where
	buf := sqlparser.NewTrackedBuffer(nil)
	where.Format(buf)
	return buf.String()
}

func ResolveSelect(stmt *sqlparser.Select) string {
	selectExprs := stmt.SelectExprs
	buf := sqlparser.NewTrackedBuffer(nil)
	selectExprs.Format(buf)
	return buf.String()
}

func ResolveFrom(stmt *sqlparser.Select) (string, string) {
	from := stmt.From
	node := from[0]
	table := node.(*sqlparser.AliasedTableExpr)
	return table.Expr.(sqlparser.TableName).Name.String(), table.As.String()
}
